package cloudjunit;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import Common.TraceWriter;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.S3Object;

public class S3FileManager
{
	private static S3FileManager inst = null;
	
	public static S3FileManager get() throws IOException
	{
		if (inst == null)
			inst = new S3FileManager();
		return inst;
	}
	
	//////////////////////

    private final AmazonS3 s3Client;
   
	
	private S3FileManager() throws IOException
	{
		this.s3Client = Config.createS3Client();
	}
	
    public void uploadFileToS3(String bucket, String localName, String remoteName)
    {
        TraceWriter.trace("uploadToS3 begin remoteName=" + remoteName + ", localName=" + localName);
        File f = new File(localName);
        s3Client.putObject(bucket, remoteName, f);
        TraceWriter.trace("uploadToS3 done");
    }
    
    public void downloadFileFromS3(String bucketName, String remoteName, String localName) throws IOException
    {
        TraceWriter.trace("downloadFileFromS3 begin bucket name = "+bucketName+" remoteName=" + remoteName + ", localName=" + localName);
        FileOutputStream f = new FileOutputStream(localName);
        try {
            S3Object obj = s3Client.getObject(bucketName, remoteName);
            InputStream inputStream = obj.getObjectContent();

            try {
                int read = 0;
                byte[] bytes = new byte[1024];
                               
                while ((read = inputStream.read(bytes)) != -1) {
                    f.write(bytes, 0, read);
                }
            }
            finally {
                inputStream.close();
            }
        }
        finally {
            f.close();
        } 
        
        TraceWriter.trace("downloadFileFromS3 done");
    }

    public void deleteLocalFiles(String fileName)
    {
        TraceWriter.trace("deleteLocalActivity begin fileName=" + fileName);
        File f = new File(fileName);
        f.delete();

        TraceWriter.trace("deleteLocalActivity done");
    }
}
